
import Toast from 'tdesign-miniprogram/toast/index';
import { submitRoomOrder } from '../../../services/api';

Page({
  data: {
    roomId: '', // 包厢号
    orderItems: [], // 订单商品列表
    totalAmount: 0, // 总金额
    isSubmitting: false, // 防止重复提交
  },

  onLoad(options) {
    const cartData = wx.getStorageSync('cartData') || [];
    
    if (cartData.length === 0) {
      Toast({
        context: this,
        selector: '#t-toast',
        message: '没有需要结算的商品',
      });
      setTimeout(() => wx.navigateBack(), 1500);
      return;
    }

    this.setData({
      roomId: getApp().globalData.roomId || '未知',
      orderItems: cartData,
      totalAmount: this.calculateTotal(cartData),
    });
  },

  calculateTotal(items) {
    const total = items.reduce((sum, item) => {
      return sum + (parseFloat(item.price) * item.quantity);
    }, 0);
    return total.toFixed(2);
  },

  onSubmit() {
    if (this.data.orderItems.length === 0 || this.data.isSubmitting) {
      return;
    }

    this.setData({ isSubmitting: true });

    const orderData = {
      roomId: this.data.roomId,
      items: this.data.orderItems,
      totalAmount: this.data.totalAmount,
    };

    submitRoomOrder(orderData).then(res => {
      if (res.success) {
        Toast({
          context: this,
          selector: '#t-toast',
          message: '下单成功，已通知后厨',
          icon: 'check-circle',
          duration: 2000,
        });

        wx.setStorageSync('cartData', []);

        setTimeout(() => {
          wx.redirectTo({
            url: '/pages/order/order-list/index',
          });
        }, 2000);
      } else {
        throw new Error('提交订单失败');
      }
    }).catch(err => {
      console.error(err);
      this.setData({ isSubmitting: false });
      Toast({
        context: this,
        selector: '#t-toast',
        message: '下单失败，请稍后重试',
        icon: 'error',
      });
    });
  },
});
